// pages/customGoodInfo/customGoodInfo.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    fileList: [],
    goodsWeight: 1,
    goodsInfoText: '',
    goodsName: '',
    goodsTypeLists: [],
    citys: [],
    senderName: '',
    senderPhone: '',
    senderAddress: '',
    consigneeName: '',
    consigneePhone: '',
    consigneeAddress: '',
    endCity: '',
    tansline_id: '',
    rate: '',
    freight: '',
    logistics_no: '',
    lock: false,
    company_id: '',
    company_type: 0
  },

  onchange(e) {
    let {
      type
    } = e.currentTarget.dataset || {}

    let data = {}
    data[type] = e.detail;
    this.setData(data)
  },

  showGoodsPopup() {
    this.setData({
      isShowGoods: true,
      goodsName: this.data.goods_type,
      goodsWeight: this.data.goodsWeight
    })
  },

  closeGoodsPopup() {
    this.setData({
      isShowGoods: false,
      goodsName: '',
      goodsWeight: ''
    })
  },

  beforeRead(event) {
    const { file, callback } = event.detail;
    callback(file.type === 'image');
  },

  afterRead(event) {
    if (this.data.isUpload) {
      return;
    }
    this.setData({
      isUpload: true
    })
    console.log(22222)
    let that = this;
    const { file } = event.detail;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    console.log('file', file);
    const fileList = that.data.fileList;
    fileList.push({ ...file, url: '', status: 'uploading' });

    this.setData({ fileList });
    wx.uploadFile({
      url: wx.$config.serverAddress + 'upimg', // 仅为示例，非真实的接口地址
      filePath: file.path,
      name: 'file',
      formData: { 'file': file.path },
      success(res) {
        let get_data = JSON.parse(res.data);
        if (get_data.code != 200) {
          wx.$Toast(get_data.msg);
          return;
        }
        // 上传完成需要更新 fileList
        // console.log('suceess', get_data);
        // fileList.push({ ...file, url: get_data.data.url });
        fileList[fileList.length - 1] = { ...file, url: get_data.data.url };
        console.log('fileList', fileList);
        that.setData({ fileList });
        that.setData({
          isUpload: false
        })
      }
    });
  },

  deleteImg(e){
    let fileList = this.data.fileList
    fileList.splice(e.detail.index, 1);
    this.setData({
      fileList: fileList
    })
  },

  /**
 * 选择货物类型
 */
  changeGoodsType: function (e) {
    let index = e.currentTarget.dataset.index;
    console.log('change_goods', index);
    let goodsName = "";
    if (index == undefined) {
      goodsName = e.detail;
    } else {
      goodsName = this.data.goodsTypeLists[index].name;
    }
    this.setData({
      goodsTypeLists: this.data.goodsTypeLists.map((item, i) => {
        if (index === i) {
          item.isActive = true;
        } else {
          item.isActive = false;
        }
        return item;
      }),
      goodsName: goodsName
    })
  },

  changeLogisticsNo(e) {
    this.setData({
      logistics_no: e.detail
    })
  },

  /**
   * 选择货物重量
   * @param {*} e 
   */
  changeGoodsWeight: function (e) {
    console.log(e)
    this.setData({
      goodsWeight: e.detail
    })
  },
  /**
  * 提交货物信息
  */
  submitGoodsInfo: function () {
    if (!this.data.goodsName) {
      return wx.$Toast('请选择货物类型');
    }

    if (!this.data.goodsWeight) {
      return wx.$Toast('请选择货物重量');
    }
    this.setData({
      isShowGoods: false,
      freight: parseInt(this.data.goodsWeight) * parseInt(this.data.rate),
      goodsInfoText: this.data.goodsName + "  " + this.data.goodsWeight + "KG"
    })
  },

  /**
 * 选择城市
 * @param {}} e 
 */
  changeCity: function (e) {
    console.log('change_city', e);
    this.setData({
      tansline_id: this.data.citys[e.detail.value].tansline_id,
      rate: this.data.citys[e.detail.value].rate,
      endCity: this.data.citys[e.detail.value].tansline_end_district,
      freight: parseInt(this.data.citys[e.detail.value].rate) * parseInt(this.data.goodsWeight)
    });
  },

  /**
 * 提交货物信息
 */
  submitMail: function () {
    if (!this.data.senderName) {
      return wx.$Toast('请输入寄件人姓名');
    }
    if (!this.data.senderPhone) {
      return wx.$Toast('请输入寄件人联系方式');
    }
    if (!this.data.consigneeName) {
      return wx.$Toast('请输入收件人姓名');
    }
    if (!this.data.consigneePhone) {
      return wx.$Toast('请输入收件人联系方式');
    }

    if (!this.data.goodsName || !this.data.goodsWeight) {
      return wx.$Toast('请选择货物信息');
    }
    if (this.data.isUpload) {
      return wx.$Toast('照片上传中，请稍候');
    }
    if (!this.data.fileList.length) {
      return wx.$Toast('请上传照片');
    }
    if(this.data.company_type == 0){
      if (!this.data.endCity) {
        return wx.$Toast('请选择送达城市');
      }
    }

    let pictures_urls = [];
    for (let val of this.data.fileList) {
      pictures_urls.push(val.url);
    }
    let post_data = {
      employee_id: wx.getStorageSync('user_id'),
      trans_line_id: this.data.tansline_id,
      post_communicate_name: this.data.senderName,
      post_communicate_mobile: this.data.senderPhone,
      depart_address: this.data.senderAddress,
      post_communicate_address: this.data.senderAddress,
      receive_communicate_name: this.data.consigneeName,
      receive_communicate_mobile: this.data.consigneePhone,
      arrive_address: this.data.consigneeAddress,
      receive_communicate_address: this.data.consigneeAddress,
      pictures_urls: pictures_urls,
      weight: this.data.goodsWeight,
      goods_type: this.data.goodsName,
      logistics_no: this.data.logistics_no,
      company_id: this.data.company_id
    };

    if(this.data.company_type == 0){
      post_data["endCity"] = this.data.endCity;
    }

    console.log(post_data)
    let { lock } = this.data;
    if (!lock) {
      this.setData({ lock: true });
      wx.$api.submitOrder(post_data).then(res => {
        console.log(res);
        if (res.data.code != 200) {
          wx.$Toast(res.data.msg);
          return;
        } else {
          this.setData({ lock: false });
        }
        wx.$Toast(res.data.msg);
        wx.navigateTo({
          url: '/pages/index/index',
        })
      })

    }
  },
  getScancode: function () {
    var _this = this;
    // 允许从相机和相册扫码
    wx.scanCode({
      scanType: ['qrCode', 'barCode'],
      success: (res) => {
        var result = res.result;
        _this.setData({
          logistics_no: result,
        })
      }
    })
  },
  getCompanyDetail(company_id) {
    wx.$api.getCompanyDetail({
      company_id: this.data.company_id
    }).then(res => {
      if (res.data.code == 200) {
        this.setData({
          goodsTypeLists: res.data.data.good_type,
          citys: res.data.data.tanslines,
          tansline_id: 0
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      company_id: options.company_id,
      company_type: options.company_type
    })
    this.getCompanyDetail(options.company_id)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})